package com.mdxq.mall.user.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.mdxq.mall.response.R;
import com.mdxq.mall.user.dto.UserLoginDTO;
import com.mdxq.mall.user.entity.Role;
import com.mdxq.mall.user.service.AdminRoleRelationService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.mdxq.mall.user.entity.Admin;
import com.mdxq.mall.user.service.AdminService;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.mdxq.mall.user.entity.table.AdminTableDef.ADMIN;

/**
 * 后台用户表 控制层。
 *
 * @author zdy
 * @since 2025-01-12
 */
@RestController
@RequestMapping("/api/v1/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminRoleRelationService adminRoleRelationService;

    @PostMapping("login")
    public R login(@RequestBody UserLoginDTO dto, HttpServletRequest request) {
        Admin admin = adminService.login(dto.getUsername(), dto.getPassword(), request);
        if (admin != null) {
            Map<String, Object> payload = new HashMap<>() {
                {
                    put("id", admin.getId());
                    put("username", admin.getUsername());
                    put("nickname", admin.getNickName());
                    //将系统时间戳放到令牌里
                    put("iat", System.currentTimeMillis());//签发时间
                    put("exp", 1 * 60 * 60 * 1000L);//有效时长
                }
            };
            String token = JWTUtil.createToken(payload, "md-mall-0112".getBytes());
            //redis存入生成的token
            redisTemplate.opsForValue().set(token,null);//redis只需哟判断key的存在
            redisTemplate.expire(token,1, TimeUnit.HOURS);
            return R.ok(token);
        }
        //401未授权
        return R.error();
    }

    /**
     * 登出功能
     * @param token
     * @return
     */
    @PostMapping("logout")
    public R logout(@RequestHeader("Authorization") String token){
        //之后加上Redis，需要登出系统时，让Redis中的token过期
        redisTemplate.delete(token);
        return R.ok(true);
    }

    /**
     * 添加后台用户表。
     *
     * @param admin 后台用户表
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("register")
    public R save(@RequestBody Admin admin) {
        return R.ok(adminService.save(admin));
    }

    /**
     * 根据主键删除后台用户表。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @PostMapping("delete/{id}")
    public R remove(@PathVariable Long id) {
        return R.ok(adminService.removeById(id));
    }

    /**
     * 根据主键更新后台用户表。
     *
     * @param admin 后台用户表
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PostMapping("update")
    public R update(@RequestBody Admin admin) {
        return R.ok(adminService.updateById(admin));
    }
    @PostMapping("updateStatus/{id}")
    public R updateStatus(@PathVariable Long id,@RequestParam Integer status) {
        Admin admin = UpdateEntity.of(Admin.class,id);
        admin.setStatus(status);
        return R.ok(adminService.updateById(admin));
    }
    /**
     * 查询所有后台用户表。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<Admin> list() {
        return adminService.list();
    }

    /**
     * 根据后台用户表主键获取详细信息。
     *
     *
     * @return 后台用户表详情
     */
    @GetMapping("getInfo")
    public R getInfo(@RequestHeader("authorization")String token) {
        //解析请求头中的token令牌，获取当前管理员的id
        JWT jwt = JWTUtil.parseToken(token);
        int adminId = Integer.valueOf(jwt.getPayload("id").toString());
        Admin admin = adminService.getById(adminId);
        return R.ok(admin);
    }

    /**
     * 分页查询后台用户表。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public R page(Page<Admin> page,String keyword) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select()
                .from(ADMIN)//"nms_admin"
                .where(ADMIN.NICK_NAME.like(keyword))//"nick_name like ''"
                .or(ADMIN.USERNAME.like(keyword));
        return R.ok(adminService.page(page,queryWrapper));
    }
    @GetMapping("role/{id}")
    public R getRole(@PathVariable Long id){
        List<Role> roleList = adminService.getRoleList(id);
        return R.ok(roleList);
    }

}
